<?php

declare(strict_types=1);

namespace app;

use owns\enum\RespCode;
use owns\library\OwnsValidate;
use think\App;
use think\exception\ValidateException;
use think\Response;

/**
 * 控制器基础类
 */
abstract class BaseController
{
    /**
     * Request实例
     * @var \think\Request
     */
    protected $request;

    /**
     * 应用实例
     * @var \think\App
     */
    protected $app;

    /**
     * 是否批量验证
     * @var bool
     */
    protected $batchValidate = false;

    /**
     * 控制器中间件
     * @var array
     */
    protected $middleware = [];

    /**
     * 构造方法
     * @access public
     * @param  App  $app  应用对象
     */
    public function __construct(App $app)
    {
        $this->app     = $app;
        $this->request = $this->app->request;
        // 控制器初始化
        $this->initialize();
    }

    // 初始化
    protected function initialize()
    {
    }

    /**
     * 验证数据
     * @param  array        $data     数据
     * @param  array        $validate 验证器名或者验证规则数组
     * @param  array        $message  提示信息
     * @param  bool         $batch    是否批量验证
     * @return array|string|true
     * @throws ValidateException
     */
    protected function validate(array $data, array $validate, array $message = [], bool $batch = false)
    {
        $v = new OwnsValidate();
        $v->rule($validate);
        $v->message($message);
        // 是否批量验证
        if ($batch || $this->batchValidate) {
            $v->batch(true);
        }
        return $v->failException(true)->check($data);
    }

    /**
     * 列表分页参数默认处理
     */
    protected function paging(): array
    {
        $param = $this->request->param();
        $param['page'] = (int) ($param['page'] ?? 1);
        $param['pageSize'] = (int) ($param['pageSize'] ?? 10);
        return $param;
    }
    /**
     * 成功
     * @param array $data 响应数据
     */
    protected function success($data = []): Response
    {
        return resp_header(null, ['code' => RespCode::SUCCESS, 'message' => '请求成功', 'data' => $data]);
    }
    /**
     * 错误
     * @param string $message 响应错误信息
     * @param mixed $data 响应数据
     */
    protected function error(string $message = '请求失败', $data = []): Response
    {
        return resp_header(null, ['code' => RespCode::ERROR, 'message' => $message, 'data' => $data]);
    }
    /**
     * 构建response
     * @param mixed $data
     * @param string $type
     * @param array $header
     * @param array $options
     */
    protected function respmake($data, $type = 'json', $header = [], $options = []): Response
    {
        return resp_header(null, $data, $type, 200, $header, $options);
    }
}
